<?php
/**
 * 文件上传处理
 */

require_once 'config/config.php';
require_once 'includes/db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

// 检查是否已安装
if (!file_exists(__DIR__ . '/config/installed.lock')) {
    echo json_encode(['success' => false, 'message' => '系统未安装，请先运行安装程序']);
    exit;
}

try {
    // 验证CSRF令牌
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        throw new Exception('安全验证失败');
    }

    // 检查文件是否上传
    if (!isset($_FILES['file']) || $_FILES['file']['error'] === UPLOAD_ERR_NO_FILE) {
        throw new Exception('请选择要上传的文件');
    }

    $file = $_FILES['file'];

    // 检查上传错误
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errors = [
            UPLOAD_ERR_INI_SIZE => '文件大小超过系统限制',
            UPLOAD_ERR_FORM_SIZE => '文件大小超过表单限制',
            UPLOAD_ERR_PARTIAL => '文件仅部分上传',
            UPLOAD_ERR_NO_FILE => '没有文件被上传',
            UPLOAD_ERR_NO_TMP_DIR => '缺少临时文件夹',
            UPLOAD_ERR_CANT_WRITE => '文件写入失败',
            UPLOAD_ERR_EXTENSION => '文件上传被扩展程序阻止'
        ];
        throw new Exception($errors[$file['error']] ?? '上传失败');
    }

    // 检查文件大小
    if ($file['size'] > MAX_FILE_SIZE) {
        throw new Exception('文件大小超过限制（最大 ' . (MAX_FILE_SIZE / 1024 / 1024) . 'MB）');
    }

    // 获取文件信息
    $originalName = $file['name'];
    $fileSize = $file['size'];
    $tmpPath = $file['tmp_name'];

    // 验证文件名
    if (empty($originalName)) {
        throw new Exception('文件名无效');
    }

    // 生成唯一文件名
    $fileExt = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    $storedName = uniqid() . '_' . time() . '.' . $fileExt;
    $uploadPath = UPLOAD_DIR . $storedName;

    // 确保上传目录存在
    if (!is_dir(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0755, true);
    }

    // 移动上传文件
    if (!move_uploaded_file($tmpPath, $uploadPath)) {
        throw new Exception('文件保存失败');
    }

    // 使用管理员密码作为删除码
    $deleteCode = ADMIN_PASSWORD;

    // 保存到数据库
    $db = new Database();
    $sql = "INSERT INTO files (original_name, stored_name, file_path, file_size, file_type, file_ext, delete_code, direct_link)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    $db->query($sql, [
        $originalName,
        $storedName,
        $uploadPath,
        $fileSize,
        $file['type'],
        $fileExt,
        $deleteCode,
        '' // 暂时留空，后续生成直链
    ]);

    $fileId = $db->getConnection()->lastInsertId();

    // 自动生成直链
    $directLink = $db->generateDirectLink($fileId);

    // 获取直链完整URL
    $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
    $directUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/direct.php?link=' . $directLink;

    echo json_encode([
        'success' => true,
        'message' => '上传成功',
        'data' => [
            'id' => $fileId,
            'name' => $originalName,
            'size' => $fileSize,
            'size_formatted' => formatFileSize($fileSize),
            'delete_code' => $deleteCode,
            'direct_link' => $directLink,
            'direct_url' => $directUrl
        ]
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * 格式化文件大小
 */
function formatFileSize($bytes) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= (1 << (10 * $pow));
    return round($bytes, 2) . ' ' . $units[$pow];
}
